<template>
  <div class="register-container">
    <!-- 星空背景 -->
    <div class="stars"></div>
    <div class="stars2"></div>
    <div class="stars3"></div>
    
    <el-card class="register-card">
      <h1 class="register-title">用户注册</h1>

      <el-form 
        @submit.prevent="handleSubmit" 
        class="register-form"
        :model="form"
        :rules="rules"
        ref="registerForm"
      >
        <el-form-item prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
            clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            v-model="form.confirmPassword"
            placeholder="请再次输入密码"
            prefix-icon="el-icon-lock"
            show-password
            clearable
          />
        </el-form-item>
        
        <!-- 角色选择 -->
        <el-form-item prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="学生" value="student"></el-option>
            <el-option label="教师" value="teacher"></el-option>
            <el-option label="管理员" value="admin"></el-option>
          </el-select>
        </el-form-item>
        
        <!-- 验证码 -->
        <el-form-item prop="captcha">
          <div class="captcha-container">
            <el-input
              v-model="form.captcha"
              placeholder="请输入验证码"
              prefix-icon="el-icon-key"
              class="captcha-input"
              maxlength="4"
            />
            <div class="captcha-image-container" @click="refreshCaptcha">
              <canvas ref="captchaCanvas" class="captcha-canvas"></canvas>
              <div class="captcha-refresh">
                <i class="el-icon-refresh"></i>
              </div>
            </div>
          </div>
        </el-form-item>

        <el-button 
          type="primary" 
          native-type="submit" 
          class="register-button" 
          :loading="isSubmitting"
        >
          立即注册
        </el-button>
      </el-form>

      <div class="login-link">
        已有账号？<router-link to="/">立即登录</router-link>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import http from "../util/request";
import { ElMessage } from "element-plus";

const router = useRouter();
const registerForm = ref(null);
const captchaCanvas = ref(null);

// 存储验证码文本
const generatedCaptcha = ref("");

const form = ref({
  username: "",
  password: "",
  role: "",
  confirmPassword: "",
  captcha: ""
});

// 校验规则
const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, message: "用户名至少3个字符", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码至少6个字符", trigger: "blur" }
  ],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    { 
      validator: (rule, value, callback) => {
        if (value !== form.value.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  role: [
    { required: true, message: "请选择角色", trigger: "change" }
  ],
  captcha: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { 
      validator: (rule, value, callback) => {
        if (value.toLowerCase() !== generatedCaptcha.value.toLowerCase()) {
          callback(new Error("验证码不正确"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

const isSubmitting = ref(false);

// 生成验证码
const generateCaptchaText = () => {
  const chars = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
  let captcha = "";
  for (let i = 0; i < 4; i++) {
    captcha += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return captcha;
};

// 绘制验证码
const drawCaptcha = (text) => {
  const canvas = captchaCanvas.value;
  if (!canvas) return;
  
  const ctx = canvas.getContext("2d");
  const width = canvas.width;
  const height = canvas.height;
  
  ctx.clearRect(0, 0, width, height);
  
  // 背景色
  ctx.fillStyle = "#f5f7fa";
  ctx.fillRect(0, 0, width, height);
  
  // 干扰线
  for (let i = 0; i < 5; i++) {
    ctx.strokeStyle = `rgb(${Math.floor(Math.random() * 100)},${Math.floor(Math.random() * 100)},${Math.floor(Math.random() * 100)})`;
    ctx.beginPath();
    ctx.moveTo(Math.random() * width, Math.random() * height);
    ctx.lineTo(Math.random() * width, Math.random() * height);
    ctx.stroke();
  }
  
  // 干扰点
  for (let i = 0; i < 50; i++) {
    ctx.fillStyle = `rgb(${Math.floor(Math.random() * 100)},${Math.floor(Math.random() * 100)},${Math.floor(Math.random() * 100)})`;
    ctx.beginPath();
    ctx.arc(Math.random() * width, Math.random() * height, 1, 0, 2 * Math.PI);
    ctx.fill();
  }
  
  // 绘制验证码字符
  const textWidth = width / text.length;
  for (let i = 0; i < text.length; i++) {
    const char = text[i];
    const x = i * textWidth + 10;
    const y = height / 2 + 10;
    
    ctx.save();
    ctx.translate(x, y);
    ctx.rotate(Math.random() * 0.4 - 0.2);
    
    ctx.font = `${Math.floor(height * 0.7)}px Arial bold`;
    ctx.fillStyle = `rgb(${Math.floor(Math.random() * 150 + 50)},${Math.floor(Math.random() * 150 + 50)},${Math.floor(Math.random() * 150 + 50)})`;
    ctx.fillText(char, 0, 0);
    
    ctx.restore();
  }
};

// 刷新验证码
const refreshCaptcha = () => {
  generatedCaptcha.value = generateCaptchaText();
  drawCaptcha(generatedCaptcha.value);
};

// 提交注册
const handleSubmit = async () => {
  try {
    await registerForm.value.validate();
    
    if (form.value.captcha.toLowerCase() !== generatedCaptcha.value.toLowerCase()) {
      ElMessage.error("验证码不正确");
      refreshCaptcha();
      return;
    }
    
    isSubmitting.value = true;
    
    await http.post('/api/register', {
      username: form.value.username,
      password: form.value.password,
      role: form.value.role
    });
    
    ElMessage.success('注册成功');
    refreshCaptcha(); // 成功后刷新验证码
    router.push('/');
  } catch (error) {
    if (error.response?.status === 409) {
      ElMessage.error('用户名已存在');
    } else if (error.response?.status === 400) {
      ElMessage.error(error.response.data.detail || '无效请求');
    } else {
      ElMessage.error(error.message || '注册失败，请稍后重试');
    }
    refreshCaptcha();
  } finally {
    isSubmitting.value = false;
  }
};

// 初始化验证码
onMounted(() => {
  const canvas = captchaCanvas.value;
  if (canvas) {
    canvas.width = 100; // 设置真实宽高
    canvas.height = 40;
  }
  refreshCaptcha();
});
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  padding: 20px;
  position: relative;
  overflow: hidden;
  background: radial-gradient(ellipse at bottom, #1B2735 0%, #090A0F 100%);
}

/* 星空背景 */
.stars, .stars2, .stars3 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: block;
}

.stars {
  background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100' viewBox='0 0 100 100'%3E%3Ccircle cx='20' cy='20' r='1' fill='%23fff'/%3E%3C/svg%3E");
  animation: animStar 100s linear infinite;
}

.stars2 {
  background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100' viewBox='0 0 100 100'%3E%3Ccircle cx='20' cy='20' r='.5' fill='%23fff'/%3E%3C/svg%3E");
  animation: animStar 150s linear infinite;
}

.stars3 {
  background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100' viewBox='0 0 100 100'%3E%3Ccircle cx='20' cy='20' r='.3' fill='%23fff'/%3E%3C/svg%3E");
  animation: animStar 200s linear infinite;
}

@keyframes animStar {
  from { transform: translateY(0px) }
  to { transform: translateY(-2000px) }
}

.register-card {
  width: 400px;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
  background-color: rgba(255, 255, 255, 0.9);
  position: relative;
  z-index: 10;
}

.register-title {
  text-align: center;
  margin-bottom: 24px;
  color: #303133;
  font-size: 24px;
}

.register-form {
  margin-top: 20px;
}

.register-button {
  width: 100%;
  margin-top: 10px;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  color: #606266;
  font-size: 14px;
}

.login-link a {
  color: #409EFF;
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}

/* 验证码样式 */
.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.captcha-input {
  flex: 1;
}

.captcha-image-container {
  position: relative;
  width: 100px;
  height: 40px;
  cursor: pointer;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  overflow: hidden;
}

.captcha-canvas {
  width: 100%;
  height: 100%;
  image-rendering: pixelated;
}

.captcha-refresh {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  width: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.7);
}

.captcha-refresh i {
  font-size: 14px;
  color: #606266;
}
</style>
